export default (dragEndFn?: Function) => {
  let startX = 0;
  let startY = 0;
  let offsetX = 0;
  let offsetY = 0;
  let dragDiv: HTMLElement | void;
  // 获取容器的宽度和高度（假设容器是浏览器窗口）
  let containerWidth = window.innerWidth;
  let containerHeight = window.innerHeight;
  function mousedownHandler(e) {
    e.stopPropagation();
    e.preventDefault();
    // 鼠标按下时记录鼠标位置和元素初始位置
    startX = e.clientX;
    startY = e.clientY;
    offsetX = this.offsetLeft;
    offsetY = this.offsetTop;
    containerWidth = window.innerWidth;
    containerHeight = window.innerHeight;
    document.addEventListener('mousemove', mousemoveHandler);
    document.addEventListener('mouseup', mouseupHandler);
  }
  function mousemoveHandler(e) {
    e.stopPropagation();
    e.preventDefault();
    if (!dragDiv) {
      return;
    }
    const deltaX = e.clientX - startX;
    const deltaY = e.clientY - startY;

    // 计算拖拽后的元素位置
    const newLeft = offsetX + deltaX;
    const newTop = offsetY + deltaY;

    // 获取容器的宽度和高度（假设容器是浏览器窗口）
    const containerWidth = window.innerWidth;
    const containerHeight = window.innerHeight;

    // 获取拖拽元素的宽度和高度
    const dragDivWidth = dragDiv.offsetWidth;
    const dragDivHeight = dragDiv.offsetHeight;
    // 计算边界值
    const maxX = containerWidth - dragDivWidth;
    const maxY = containerHeight - dragDivHeight;

    // 确保拖拽元素不超出边界
    if (newLeft >= 0 && newLeft <= maxX) {
      dragDiv.style.left = newLeft + 'px';
    }
    if (newTop >= 0 && newTop <= maxY) {
      dragDiv.style.top = newTop + 'px';
    }
  }

  function mouseupHandler(e) {
    e.stopPropagation();
    e.preventDefault();
    document.removeEventListener('mousemove', mousemoveHandler);
    document.removeEventListener('mouseup', mouseupHandler);
    if (dragEndFn) {
      dragEndFn();
    }
  }
  const setDragAble = (dragDivDom: HTMLElement) => {
    dragDiv = dragDivDom;
    dragDiv.addEventListener('mousedown', mousedownHandler);
  };
  const removeDragAble = (dragDivDom: HTMLElement) => {
    dragDivDom.removeEventListener('mousedown', mousedownHandler);
  };
  return {
    setDragAble,
    removeDragAble
  };
};
